<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Library as LibraryMdl;
use app\admin\model\Librarytype;
use app\admin\model\Libraryopen;
use app\admin\model\Libraryfolder;
use app\admin\model\Userfolder;
use app\admin\model\User;
use app\admin\model\Member;
use app\admin\model\Operator;
use app\admin\model\Image;
use app\admin\service\Library as LibraryService;

use think\Db;
use think\Exception;
use think\Request;

class Library extends BaseController
{

    /**
     * 首页
     */
    public function getHome()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $userId = $param->userId;
        $data = [];
        if ($param->type == 1) {
            // 我的文库
            $model = new Userfolder();
            // 是否存在默认目录
            $defaultFolder = $model->where(['userId' => $param->userId, 'isDefault' => 1])->find();
            if (!$defaultFolder) {
                $folderData = [
                    'id' => BaseHelper::getUUID(),
                    'createDate' => time(),
                    'userId' => $param->userId,
                    'name' => 'Default',
                    'isDefault' => 1
                ];
                $model->insert($folderData);
            }

            $where = [
                'userId' => $userId
            ];
            $order = 'createDate DESC';
            if(!empty($param->order) && $param->order == 2){
                $order = 'name ASC';
            }
            $data = $model->where($where)->order($order)->select();
        } else {
            // 共享文库
            $librarytype = $this->getFileTypes();

            // 精选推荐
            $ids = $this->getAllowLibraryIds($userId); // 获取可见的文件ID集合
            $librarys = LibraryMdl::alias('a')
                ->where(['a.id' => ['in', $ids], 'a.isDelete' => 2])
                //->join('__MEMBER__ m' ,'a.createOper = m.id')
                ->field('a.id, a.createDate, a.createOper, a.typeId, a.name, a.fileUrl, a.fileType')
                ->order('a.createDate')
                ->limit(0, 20)
                ->select();

            foreach ($librarys as $library) {
                $operatorInfo = Operator::where(['id' => $library['createOper']])->field('loginName, memberId')->find();
                if ($operatorInfo) {
                    // 后台上传
                    $createOperName = $operatorInfo['loginName'];
                    $createOperAvatar = '';
                    if ($operatorInfo['memberId']) {
                        $memberInfo = Member::where(['id' => $operatorInfo['memberId']])->field('name, avatar')->find();
                        $createOperName = $memberInfo['name'];
                        $createOperAvatar = $memberInfo['avatar'];
                    }
                } else {
                    // 前端上传
                    $memberInfo = Member::where(['id' => $library['createOper']])->field('name, avatar')->find();
                    $createOperName = $memberInfo['name'];
                    $createOperAvatar = $memberInfo['avatar'];
                }

                $library['userName'] = $createOperName;
                $library['userAvatar'] = $createOperAvatar;
            }

            $data = [
                'librarytype' => $librarytype,
                'librarys' => $librarys
            ];
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 获取可见的文件ID集合
     */
    private function getAllowLibraryIds($userId)
    {
        $libraryMdl = new LibraryMdl();
        $ids = [];
        // 所有人公开
        $allOpenIds = $libraryMdl->where(['openType' => 0, 'isDelete' => 2])->column('id');

        $memberId = User::where('id', $userId)->value('memberId');
        if ($memberId) {
            // 部分人公开
            $openIds = Libraryopen::alias('a')->where(['a.memberId' => $memberId, 'b.openType' => 1])->join('library b', 'a.libraryId = b.id')->column('a.libraryId');
            // 上传者
            $uploadIds = $libraryMdl->where(['openType' => 2, 'createOper' => $memberId, 'isDelete' => 2])->column('id');
        } else {
            $openIds = [];
            $uploadIds = [];
        }
        $ids = array_merge($allOpenIds, $openIds, $uploadIds);
        // 去重
        $ids = array_unique($ids);

        return $ids;
    }

    /**
     * 获取文件分类
     */
    private function getFileTypes()
    {
        $model = new Librarytype();
        $where = [];
        $order = 'sorting ASC';
        $librarytype = $model->where($where)->field('id, name, imgUrl')->order($order)->select();
        if(!$librarytype){
            return [];
        }

        return $librarytype;
    }

    /**
     * 创建/保存文件夹
     */
    public function saveFolder()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->name)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '项目名(name) 不能为空');
        }

        Db::startTrans();
        try {
            $data = (array)$param;
            $model = new Userfolder();

            if (!empty($param->id)) {
                $id = $param->id;
                $data['updateDate'] = time();
                $message = '保存失败';

                $result = $model->allowField(true)->save($data, ['id' => $id]);
            } else {
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();
                $message = '创建失败';

                $result = $model->save($data);
            }

            if($result !== false){
                Db::commit();
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), $message, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '操作失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, []);
    }

    /**
     * 删除文件夹
     */
    public function delFolder()
    {
        $param = self::getHttpParam();

        if (empty($param->folderId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'folderId 不能为空');
        }

        $folderId = $param->folderId;
        $where = [
            'id' => $folderId
        ];

        Db::startTrans();
        $model = new Userfolder();
        $result = $model->where($where)->delete();
        if ($result === false) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
        }

        // 删除文件夹下的文件
        $res = Libraryfolder::where(['folderId' => $folderId])->delete();
        if($res === false){
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除文件夹下文件失败');
        }
        Db::commit();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /**
     * 文件列表
     */
    public function getFileTypeList()
    {
        //$param = self::getHttpParam();
        $data = $this->getFileTypes();
        if(!$data){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 文件列表--共享文库
     */
    public function getFileList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        /*if (empty($param->typeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'typeId 不能为空');
        }*/
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            //'typeId' => $param->typeId,
            'isDelete' => 2
        ];
        if(!empty($param->typeId)){
            $where['typeId'] = $param->typeId;
        }
        $ids = $this->getAllowLibraryIds($param->userId); // 获取可见的文件ID集合
        $where['id'] = ['in', $ids];

        if(!empty($param->keyword)){
            // 关键字
            $where['name'] = ['like', '%' . $param->keyword . '%'];
        }

        $model = new LibraryMdl();
        $fields = '*';
        $order = 'createDate DESC';
        if(!empty($param->order) && $param->order == 2){
            // 下载最多
            $order = 'countDownload DESC';
        }
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        foreach ($result as $item) {
            // 上传者信息
            $operatorInfo = Operator::where(['id' => $item['createOper']])->field('loginName, memberId')->find();
            if ($operatorInfo) {
                // 后台上传
                $createOperName = $operatorInfo['loginName'];
                $createOperAvatar = '';
                if ($operatorInfo['memberId']) {
                    $memberInfo = Member::where(['id' => $operatorInfo['memberId']])->field('name, avatar')->find();
                    $createOperName = $memberInfo['name'];
                    $createOperAvatar = $memberInfo['avatar'];
                }
            } else {
                // 前端上传
                $memberInfo = Member::where(['id' => $item['createOper']])->field('name, avatar')->find();
                $createOperName = $memberInfo['name'];
                $createOperAvatar = $memberInfo['avatar'];
            }

            $item['userName'] = $createOperName;
            $item['userAvatar'] = $createOperAvatar;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 文件列表--我的文件夹
     */
    public function getMyFiles()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->folderId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'folderId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $folderId = $param->folderId;
        $where = [
            'folderId' => $folderId
        ];

        $model = new Libraryfolder();
        $fields = '*';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 文件转移
     */
    public function moveMyFile() {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->fileIds)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'fileIds 不能为空');
        }
        if (empty($param->folderId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'folderId 不能为空');
        }

        $folderId = $param->folderId;
        $model = new Libraryfolder();

        $ids = (Array)$param->fileIds;
        foreach ($ids as $id) {
            $result = $model->where('id', $id)->update(['folderId' => $folderId]);
        }

        if ($result === false) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '移动失败！');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '移动成功！');
    }

    /**
     * 删除文件
     */
    public function delMyFile() {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->fileId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'fileId 不能为空');
        }

        $where = [
            'id' => $param->fileId
        ];
        $model = new Libraryfolder();
        $result = $model->where($where)->delete();
        if ($result === false) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '删除成功！');
    }

    /**
     * 上传文件/修改
     */
    public function uploadFile()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->folderId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '文件夹ID(folderId) 不能为空');
        }
        if (empty($param->name)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '文件名称(name) 不能为空');
        }
        if (empty($param->typeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '分类ID(typeId) 不能为空');
        }
        if (empty($param->openType) && $param->openType != 0) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '公开类型(openType) 不能为空');
        }

        Db::startTrans();
        try {
            $data = (array)$param;
            //$data['fileName'] = '';
            if($data['fileUrl']){
                @$data['fileType'] = pathinfo($data['fileUrl'], PATHINFO_EXTENSION);
            }

            $model = new LibraryMdl();

            $memberId = User::where('id', $param->userId)->value('memberId');
            $area = $this->getParentIdsByTownId($data['townId']);
            $data['cityId'] = $area['cityId'];
            $data['xianId'] = $area['xianId'];
            $data['createOper'] = $memberId;
            $data['isDelete'] = 2;
            if (!empty($param->id)) {
                $id = $param->id;
                $data['id'] = $id;
                $data['updateDate'] = time();

                $result = $model->allowField(true)->save($data, ['id' => $id]);
            } else {
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();

                $result = $model->save($data);
            }

            if($result === false){
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '上传失败', $model->getError());
            }

            if(isset($data['openmemberIds']) && $data['openmemberIds']){
                $data['openmemberIds'] = implode(',', $data['openmemberIds']);
            }

            // 保存公开人员
            $res = LibraryService::saveLibraryopen($data);
            if($res['code'] != 1){
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '上传失败', $res['msg']);
            }

            // 上传到我的文件夹下
            $libData = [
                'createDate' => time(),
                'libraryId' => $data['id'],
                'folderId' => $param->folderId,
                'fileUrl' => $param->fileUrl,
                'fileType' => $data['fileType'],
                'fileName' => $param->name,
                'type' => 1
            ];
            $libRes = Libraryfolder::insert($libData);
            if($libRes === false){
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '上传到我的文件夹失败', Libraryfolder::getError());
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '上传失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, []);
    }

    /**
     * 文件下载
     */
    /*public function downloadFile()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->fileId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'fileId 不能为空');
        }

        // 下载次数 +1
        $res = LibraryMdl::where('id', $param->fileId)->setInc('countDownload');

        // TODO
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, []);
    }*/

}